<template>
  <!-- 条形码打印 -->

  <div>
    <el-dialog
      title="产品条码打印"
      :visible.sync="dialogVisible"
      width="50%"
      :close-on-click-modal="false"
      destroy-on-close
      :before-close="handleClose"
    >
      <el-row>
        <el-table :data="tableData" border :max-height="600" style="width: 100%">
          <el-table-column prop="sku" label="SKU" header-align="center" align="center"> </el-table-column>
          <el-table-column prop="name" label="产品名称" header-align="center" align="center"> </el-table-column>
          <el-table-column label="打印数量" header-align="center" align="center" width="180">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.printQuantity"
                :min="1"
                :max="100"
                style="min-width:150px;max-width:200px;"
                label="请输入"
              ></el-input-number>
            </template>
          </el-table-column>
        </el-table>
      </el-row>

      <el-form :model="infoModuler" ref="ruleForm" label-width="160px" class="mtop30">
        <el-row>
          <el-col :span="24">
            <el-form-item label="打印尺寸：">
              <el-radio-group v-model="infoModuler.printSize" @change="changeGroup(0, 'size')">
                <el-radio label="1">50x30</el-radio>
                <el-radio label="2">70x30</el-radio>
                <el-radio label="3">100x30</el-radio>
                <el-radio label="4">100x100</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="打印类型：">
              <el-radio-group v-model="infoModuler.printType" @change="changeGroup(0, 'dataType')">
                <el-radio label="1">产品SKU</el-radio>
                <el-radio label="2">客户代码+SKU</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="附加信息：">
              <el-checkbox-group v-model="infoModuler.additionalInfo" @change="changeGroup(0, 'addInfo')">
                <el-checkbox label="1">产品名称</el-checkbox>
                <el-checkbox label="2">产品名称(EN)</el-checkbox>
                <el-checkbox label="3">Made in China</el-checkbox>
                <el-checkbox label="4">日期</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row class="flexCenter">
          <div id="demo" class="barcode flexCenter flexbox_column" ref="demo">
            <div class="addinfo" ref="addinfo1" v-if="printInfo.name">{{ printInfo.name }}</div>
            <div class="addinfo" ref="addinfo2" v-if="printInfo.en_name">{{ printInfo.en_name }}</div>
            <canvas id="barcode" ref="barcode"></canvas>

            <div class="addinfo" ref="addinfo3" v-if="printInfo.Country">{{ printInfo.Country }}</div>
            <div class="addinfo" ref="addinfo4" v-if="printInfo.create_time">{{ printInfo.create_time }}</div>
          </div>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" icon="el-icon-printer" @click="Print_quantity">打印</el-button>

        <el-button type="primary" @click="print_pdf">生成pdf</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import JsBarcode from 'jsbarcode'
import htmlToPdf from '@/libs/htmlToPdf.js'
// import { getLodop } from '@/libs/LodopFuncs'
import getLodop from '@/libs/load-lodop'

export default {
  name: 'barCode',
  mixins: [htmlToPdf],
  props: {
    showModal: {
      type: Boolean,
      default: false,
    },

    selectData: {
      type: Array,
      default: () => [],
    },
  },

  watch: {
    showModal: {
      handler(val) {
        if (val) {
          this.dialogVisible = val
          this.tableData = this.selectData

          this.LODOP = getLodop()
          this.$nextTick(() => {
            this.changeGroup()
            // this.init()
          })
        }
      },
      deep: true,
    },
  },

  data() {
    return {
      LODOP: null,
      top: 0,

      printInfo: { additional_info: '', name: '', en_name: '', Country: '', create_time: '' },
      tableData: [],
      infoModuler: {
        operationType: '2',
        printSize: '1',
        printType: '1',
        additionalInfo: ['1'],
      },
      codetitle: '独立产品条形码',
      save_loading: false,
      dialogVisible: this.showModal,
      barcodeInfo: {},
    }
  },

  methods: {
    changeGroup(i = 0) {
      console.log(i, 'i====')
      const params = this.selectData[i]
      const { printType, additionalInfo } = this.infoModuler
      if (printType == '1') {
        this.infoModuler.data = params.sku
      } else if (printType == '2') {
        this.infoModuler.data = `${params.creator_code}-${params.sku}`
      }

      additionalInfo.forEach(e => {
        if (e.includes('1')) {
          this.printInfo.name = params.name
        } else if (e.includes('2')) {
          this.printInfo.en_name = params.en_name
        } else if (e.includes('3')) {
          this.printInfo.Country = 'Made in China'
        } else if (e.includes('4')) {
          this.printInfo.create_time = params.create_time
        }
      })

      this.$forceUpdate()

      this.getBarcode(this.infoModuler.data)
    },

    getBarcode(data1) {
      console.log(data1)
      if (!data1) return
      const options = {
        // text: data1,
        displayValue: true,
        fontSize: 20,
        textMargin: 1,
        height: 70,
        width: 1.5,
      }

      this.$nextTick(() => {
        JsBarcode('#barcode', data1, options)
      })
    },

    // 打印pdf
    print_pdf() {
      this.btnClickPrint()
      this.LODOP.PRINT()
    },

    // 直接打印数量
    Print_quantity() {
      this.btnClickPrint(0)
      // const flag = this.btnClickPrint(0)
      // if (flag == 2) {
      //   this.$message({
      //     message: '请输入打印数量',
      //     type: 'warning',
      //   })
      //   return
      // }
      // if (flag == 1) {
      //   this.$message({
      //     message: '请检查lodop 打印控件是否安装',
      //     type: 'warning',
      //   })
      //   return
      // }
      // this.LODOP.PREVIEW() // 打印预览
      // this.LODOP.PRINT_DESIGN() // 打印设计
    },

    btnClickPrint: function(idex) {
      let count = 0
      this.tableData.forEach(item => {
        count += item.printQuantity
      })

      if (count > 0) {
        if (this.LODOP) {
          const box = document.getElementById('demo')
          const canvasImg = this.$refs.barcode.toDataURL()
          let page = 1

          let strBodyStyle = '<body style="display: flex; flex-direction: column; align-items: center; justify-content: center;color:#2f2f2f;">'
          if (canvasImg) {
            if (this.printInfo.name) {
              strBodyStyle += `<div style="color:#2f2f2f;">${this.$refs.addinfo1.innerHTML}</div>`
            }
            if (this.printInfo.en_name) {
              strBodyStyle += `<div style="color:#2f2f2f;">${this.$refs.addinfo2.innerHTML}</div>`
            }

            strBodyStyle += `<div><img src="${canvasImg}" /></div>`
            // this.LODOP.ADD_PRINT_BARCODE(40, '2mm', '79mm', 85, '128C', this.infoModuler.data)

            if (this.printInfo.Country) {
              strBodyStyle += `<div style="color:#2f2f2f;">${this.$refs.addinfo3.innerHTML}</div>`
            }
            if (this.printInfo.create_time) {
              strBodyStyle += `<div style="color:#2f2f2f;">${this.$refs.addinfo4.innerHTML}</div>`
            }
            // console.log(box.clientWidth)
            if (idex == 0) {
              this.LODOP.PRINT_INIT('')
            }
            const list = this.tableData[idex]
            let h = 0
            // const top = 0
            for (let i = 0; i < list.printQuantity; i++) {
              if (i > 1 && i % 2 === 0) {
                if (i == 2 || i == 3) {
                  h += 40
                } else {
                  h += box.clientHeight + 40
                }
                this.top = box.clientHeight + h
              }
              if (i % 2 === 0) {
                this.LODOP.ADD_PRINT_HTM(this.top, 400, box.clientWidth, box.clientHeight, strBodyStyle)
                // this.LODOP.ADD_PRINT_HTM(this.top, 400, box.clientWidth, box.clientHeight, this.LODOP.ADD_PRINT_BARCODE(40, '2mm', '79mm', 85, '128Auto', item.sku))
              } else {
                this.LODOP.ADD_PRINT_HTM(this.top, 60, box.clientWidth, box.clientHeight, strBodyStyle)
                // this.LODOP.ADD_PRINT_HTM(this.top, 60, box.clientWidth, box.clientHeight, this.LODOP.ADD_PRINT_BARCODE(40, '2mm', '79mm', 85, '128Auto', item.sku))
              }

              if (i % 12 === 0) {
                page++
              }
            }
            if (this.tableData.length - 1 > idex) {
              // console.log(this.tableData.length, idex)
              this.top = 0
              this.LODOP.NEWPAGE()
              this.changeGroup(idex + 1) // 更新dom数据
              this.$forceUpdate()

              const times = setTimeout(() => {
                clearTimeout(times)
                this.btnClickPrint(idex + 1)
              }, 500)
              // return
            } else {
              this.LODOP.SET_PRINT_COPIES(page) // 页数
              this.LODOP.PREVIEW() // 打印预览
            }
          }
        } else {
          this.$message({
            message: '请检查lodop 打印控件是否安装',
            type: 'warning',
          })
        }
      } else {
        this.$message({
          message: '请输入打印数量',
          type: 'warning',
        })
      }
    },

    handleClose() {
      this.save_loading = false
      this.dialogVisible = false
      this.$emit('update:showModal', this.dialogVisible)
    },
  },
}
</script>

<style lang="scss" scoped>
.barcode {
  width: auto;
  height: 100%;

  .addinfo {
    font-size: 15px;
    color: #2f2f2f;
    margin-top: 4px;
  }

  .icons {
    font-size: 26px;
    cursor: pointer;
  }

  .mright30 {
    margin-right: 30px;
  }
}
</style>
